package org.jeecg.modules.sggg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.ToolUtils;
import org.jeecg.modules.sggg.entity.SgServiceItem;
import org.jeecg.modules.sggg.entity.SgSigningRecord;
import org.jeecg.modules.sggg.service.ISgServiceItemService;
import org.jeecg.modules.sggg.service.ISgSigningRecordService;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 签约表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "签约表")
@RestController
@RequestMapping("/sggg/sgSigningRecord")
@Slf4j
public class SgSigningRecordController extends JeecgController<SgSigningRecord, ISgSigningRecordService> {
    @Autowired
    private ISgSigningRecordService sgSigningRecordService;

    @Autowired
    private ISgServiceItemService sgServiceItemService;

    @Autowired
    private ToolUtils toolUtils;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISysRoleService sysRoleRoleService;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 三高签约记录
     *
     * @param sgSigningRecord 签约对象
     * @param pageNo          当前第几页
     * @param pageSize        一页多少条
     * @return 当前页数据
     */
    @ApiOperation(value = "签约表-分页列表查询", notes = "签约表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgSigningRecord>> queryPageList(SgSigningRecord sgSigningRecord,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgSigningRecord> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysRole> roleList = sysRoleRoleService.getUserRole(sysUser.getId());
        String code = "";
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin")) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            //机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgSigningRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgSigningRecord.setResponsibleAgencies(responsibleAgencies);
            }
        }else{
            sysUser.setId(sysUser1.getId());
        }
        IPage<SgSigningRecord> pageList = sgSigningRecordService.pageList(page, sgSigningRecord, sysUser.getOrgCode(), code, sysUser.getId());
        return Result.OK(pageList);
    }

    @ApiOperation(value = "签约表-续约列表", notes = "签约表-续约列表")
    @GetMapping(value = "/renewalList")
    public Result<IPage<SgSigningRecord>> renewalList(SgSigningRecord sgSigningRecord,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgSigningRecord> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        if(roleCode.contains("dept_manage") || roleCode.contains("admin")){
            sgSigningRecord.setSysOrgCode(sysUser1.getOrgCode());
        }
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgSigningRecord.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgSigningRecord.setResponsibleAgencies(responsibleAgencies);
            }
        }else{
            sysUser.setId(sysUser1.getId());
        }
        IPage<SgSigningRecord> pageList = sgSigningRecordService.renewalListTo(page, sgSigningRecord, sysUser.getId());
        return Result.OK(pageList);
    }

    /**
     * lx ---- 2022年11月18日 居民信息，签约记录(小程序也用)
     *
     * @param mid 居民id
     * @return 当前页结果
     */
    @GetMapping("/queryListByMid")
    public Result<List<SgSigningRecord>> queryListByMid(String mid) {
        return Result.OK(sgSigningRecordService.getSigningRecord(mid));
    }

    @ApiOperation(value = "签约表-续约", notes = "签约表-续约")
    @PostMapping(value = "/renewal")
    public Result<String> renewal(@RequestBody SgSigningRecord s) {
        s.setEndTime(toolUtils.addDate(s.getStartTime(), s.getDayNum()));
        sgSigningRecordService.updateById(s);
        return Result.OK("续约成功！");
    }

    /**
     * 签约
     *
     * @param list 集合
     * @return 结果
     */
    @PostMapping("/signing")
    public Result<String> signing(@RequestBody List<SgSigningRecord> list) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String idOrder = String.valueOf(System.currentTimeMillis());
        list.forEach(s -> {
            s.setIdOrder(s.getMemberId() + idOrder);
            s.setEndTime(toolUtils.addDate(s.getStartTime(), s.getDayNum()));
            s.setUserId(user.getId());
            sgSigningRecordService.save(s);
        });
        return Result.OK("签约成功！");
    }

    /**
     * 三高签约记录 》 查看时要用到
     *
     * @param idOrder idOrder
     * @return 服务项列表
     */
    @GetMapping("queryServiceItemByIdOrder")
    public Result<List<SgServiceItem>> queryServiceItemByIdOrder(String idOrder) {
        List<String> ids = new ArrayList<>();
        sgSigningRecordService.list(
                new QueryWrapper<SgSigningRecord>()
                        .eq("id_order", idOrder)
                        .select("service_tid")
        ).forEach(s -> ids.add(s.getServiceTid()));
        return Result.OK(sgServiceItemService.list(new QueryWrapper<SgServiceItem>().in("id", ids)));
    }

    @AutoLog(value = "签约表-通过id删除")
    @ApiOperation(value = "签约表-通过id删除", notes = "签约表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgSigningRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    @ApiOperation(value = "签约表-通过id查询", notes = "签约表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgSigningRecord> queryById(@RequestParam(name = "id") String id) {
        SgSigningRecord sgSigningRecord = sgSigningRecordService.getById(id);
        if (sgSigningRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgSigningRecord);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgSigningRecord sgSigningRecord) {
        return super.exportXls(request, sgSigningRecord, SgSigningRecord.class, "签约表");
    }

    /**
     * 根据居民id获取签约记录
     *
     * @param memberId
     * @return
     */
    @GetMapping("/getSigningRecordByMid")
    public Result<List<SgSigningRecord>> getSigningRecordByMid(String memberId) {
        List<SgSigningRecord> signingRecords = sgSigningRecordService.getSigningRecordByMid(memberId);
        return Result.ok(signingRecords);
    }
}
